//
//  NSTextField+KeyEquivalent.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/10/16.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation


extension NSTextField {
    override open func performKeyEquivalent(with event: NSEvent) -> Bool {
        let modifierkeys = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
        let key = event.characters ?? ""
        /// 点击 esc 取消焦点
        if modifierkeys.rawValue == 0 && key == "\u{1B}" {
            self.window?.makeFirstResponder(nil)
        }
        // command + shift + z 还原
        if modifierkeys == [.command, .shift] && key == "z" {
            self.window?.firstResponder?.undoManager?.redo()
            return true
        }
        if modifierkeys != .command {
            return super.performKeyEquivalent(with: event)
        }
        switch key {
        case "a":  // 撤消
            return NSApp.sendAction(#selector(NSText.selectAll(_:)), to: self.window?.firstResponder, from: self)
        case "c":  // 复制
            return NSApp.sendAction(#selector(NSText.copy(_:)), to: self.window?.firstResponder, from: self)
        case "v":  // 粘贴
            return NSApp.sendAction(#selector(NSText.paste(_:)), to: self.window?.firstResponder, from: self)
        case "x":  // 剪切
            return NSApp.sendAction(#selector(NSText.cut(_:)), to: self.window?.firstResponder, from: self)
        case "z":  // 撤消
            self.window?.firstResponder?.undoManager?.undo()
            return true
        default:
            return super.performKeyEquivalent(with: event)
        }
    }
}
